/*
* 开始检查
* */

import 'dart:convert';

import 'package:center_beijing/api/product_api.dart';
import 'package:center_beijing/api/task_api.dart';
import 'package:center_beijing/common/logutil.dart';
import 'package:center_beijing/common/notification.dart';
import 'package:center_beijing/common/styles.dart';
import 'package:center_beijing/config/global_config.dart';
import 'package:center_beijing/models/selectItem.dart';
import 'package:center_beijing/widgets/custom_loading_widget.dart';
import 'package:center_beijing/widgets/custom_radio.dart';
import 'package:center_beijing/widgets/imageSelect_widget.dart';
import 'package:center_beijing/widgets/textarea_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart' as Go;
import 'package:dio/dio.dart' as ImageForm;
import 'dart:io';

import 'package:images_picker/images_picker.dart';
import 'package:http_parser/http_parser.dart';
class AddEquipmentInspection extends StatefulWidget {
  @override
  _AddEquipmentInspectionState createState() => _AddEquipmentInspectionState();
}

class _AddEquipmentInspectionState extends State<AddEquipmentInspection>
    with SingleTickerProviderStateMixin {
  AnimationController _controller;
  CustomLoading loading = CustomLoading.withMessage('提交中...');
  var equipment = Go.Get.arguments['equipment'];
  var planId = Go.Get.arguments['planId'];
  List dataSource = [];
  List selectList = [];
  List<Media> photos = [];
  List passPhoto = [];
  String remark = '';
  ImageForm.FormData formData;

  @override
  void initState() {
    _controller = AnimationController(vsync: this);
    super.initState();
    this.getEquipmentTask();
  }

  getEquipmentTask() async {
    var pass = {
      'planId': planId,
      'equipmentId': equipment['id'],
    };
    var result = await getEquipmentCheckInfo(pass);
    if (result != null) {
      result.forEach((element) {
        selectList.add({'infoId': element['id'], 'checkResult': '1'});
      });
      this.setState(() {
        dataSource = result;
      });
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    loading.dismiss();
    super.dispose();
  }


  /*
  * 提交
  * */
  submit() async {
    var pass = {
      'planId': planId,
      'equipmentId': equipment['id'],
      'checkResult': remark,
      'fileList': json.encode(this.passPhoto),
      'checkRecordList': json.encode(selectList.map((e) {
        return {'infoId': e['infoId'], 'checkResult': e['checkResult']};
      }).toList())
    };
    var result = await saveCheckRecord(pass);
    loading.dismiss();
    if (result['text'] != null && result['text'] == '') {
      bus.emit('refreshEquipList');
      bus.emit('refreshEquipmentTask');
      Fluttertoast.showToast(msg: '提交完成');
      Go.Get.back();
    }
  }

  Future addImage() async {
    this.passPhoto = [];
    loading.show(delay: 30);
    if (this.photos.length > 0) {
      var temPhotos = [];
      temPhotos.addAll(this.photos);
      formData = new ImageForm.FormData.fromMap({
        "tenantId": GlobalConfig.tenantId,
      });
      for (int i = 0; i < temPhotos.length; i++) {
        Media asset = temPhotos[i];
        File file = File(asset.path);
        formData.files.add(MapEntry("files",
            await ImageForm.MultipartFile.fromFile(file.path.toString(),contentType: MediaType('image',file.path.toString().split('.').last))));
      }
      var result = await uploadImage(formData, GlobalConfig.tenantId);
      if (result != null && result.length > 0) {
        this.passPhoto = [];
        result.forEach((item) {
          this.passPhoto.add({
            'fileId': item['attachmentId'],
            'fileName': item['fileName'],
            'fileType': item['fileName'].split('.').last
          });
        });
        LogUtil.d(this.passPhoto);
        this.submit();
      }
    } else {
      this.submit();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('设备巡检'),
        ),
        body: Container(
          color: Styles.MainBackgroundColor,
          padding: EdgeInsets.fromLTRB(
              0, 0, 0, MediaQuery.of(context).padding.bottom + 70),
          child: GestureDetector(
            onTap: (){
              FocusScope.of(context).requestFocus(FocusNode());
            },
            child: Column(
              children: [
                Container(
                  padding: EdgeInsets.fromLTRB(Styles.spacing8, Styles.spacing8,
                      Styles.spacing8, Styles.spacing8),
                  child: Row(
                    children: [
                      Container(
                        height: 26.h,
                        width: 4,
                        color: Styles.BlueColor,
                        margin: EdgeInsets.only(right: Styles.spacing8),
                      ),
                      Text(
                        '待检查设备',
                        style: TextStyle(
                            color: Styles.DetailColor,
                            fontSize: Styles.Middle16Font),
                      ),
                    ],
                  ),
                ),
                Container(
                  color: Colors.white,
                  padding: EdgeInsets.fromLTRB(Styles.spacing16, Styles.spacing8,
                      Styles.spacing16, Styles.spacing8),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      equipment['equipmentPhoto'] != null
                          ? Container(
                        child: Image.network(
                          "${GlobalConfig.baseUrl}fs/irest/file/mps_fileTransferHandler/image?id=${equipment['equipmentPhoto']}&ZJQFSESSION=${GlobalConfig.session}",
                          height: 80.h,
                          width: 80.w,
                          fit: BoxFit.fill,
                        ),
                      )
                          : Container(
                          child: Image.asset(
                            'assets/images/default_image.png',
                            height: 80.h,
                            width: 80.w,
                            fit: BoxFit.fill,
                          )),
                      Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Container(
                                alignment: Alignment.centerLeft,
                                margin: EdgeInsets.fromLTRB(
                                    Styles.spacing8, 0, Styles.spacing8, 0),
                                child: Text(
                                  equipment['equipmentName'] != null
                                      ? equipment['equipmentName']
                                      : '--',
                                  style: TextStyle(
                                      color: Styles.DetailColor,
                                      fontSize: Styles.Middle16Font),
                                ),
                              ),
                              Container(
                                alignment: Alignment.centerLeft,
                                margin: EdgeInsets.fromLTRB(Styles.spacing8,
                                    Styles.spacing8, Styles.spacing8, 0),
                                child: Text(
                                  equipment['address'] != null
                                      ? equipment['address']
                                      : '--',
                                  style: TextStyle(
                                      color: Styles.DetailColor,
                                      fontSize: Styles.NormalFont),
                                ),
                              ),
                            ],
                          ))
                    ],
                  ),
                ),
                Expanded(
                    child: SingleChildScrollView(
                      child: Column(
                        children: [
                          Column(
                            children: dataSource.asMap().keys.map((index) {
                              return CustomRadio(
                                title: dataSource[index]['checkName'],
                                selectList: [
                                  SelectItems(
                                      label: '是',
                                      value: '1',
                                      flag: dataSource[index]['id']),
                                  SelectItems(
                                      label: '否',
                                      value: '0',
                                      flag: dataSource[index]['id'])
                                ],
                                selectCallback: (item) {
                                  var bbq = selectList[index];
                                  bbq['infoId'] = item.flag;
                                  bbq['checkResult'] = item.value;
                                },
                              );
                            }).toList(),
                          ),
                          Container(
                            color: Colors.white,
                            margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                            padding: EdgeInsets.fromLTRB(
                                Styles.spacing8, 0, Styles.spacing8, 0),
                            child: TextAreaWidget(
                              maxLength: 100,
                              labelText: '巡检信息',
                              defaultValue: '',
                              placeholder: '请输入巡检信息',
                              disabled: false,
                              required: false,
                              rows: 4,
                              onChange: (value) => this.setState(() {
                                remark = value;
                              }),
                            ),
                          ),
                          Container(
                            margin: EdgeInsets.fromLTRB(0, Styles.spacing8, 0, 0),
                            color: Colors.white,
                            child: Column(
                              children: [
                                Padding(
                                  padding: EdgeInsets.fromLTRB(
                                      Styles.spacing16, Styles.spacing8, 0, 0),
                                  child: Row(
                                    children: <Widget>[
                                      Text(
                                        '现场照片(${this.photos.length}/6)',
                                        style: TextStyle(
                                            color: Styles.DetailColor,
                                            fontSize: Styles.MiddleFont17),
                                      ),
                                    ],
                                  ),
                                ),
                                ImageSelectWidget(
                                  onchange: (value) {
                                    this.setState(() {
                                      photos = value;
                                    });
                                  },
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ))
              ],
            ),
          ),
        ),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
        floatingActionButton: Container(
          padding: EdgeInsets.fromLTRB(
              Styles.spacing8, Styles.spacing8, Styles.spacing8, 10),
          child: Container(
            decoration: new BoxDecoration(
              //背景
              color: Styles.BlueColor,
              //设置四周圆角 角度
              borderRadius: BorderRadius.all(Radius.circular(12.0)),
            ),
            child: FlatButton(
              disabledColor: Styles.SelectColor,
              onPressed: () {
                FocusScope.of(context).requestFocus(new FocusNode());
                showDialog(
                    barrierDismissible: false,
                    context: this.context,
                    builder: (BuildContext context) {
                      return AlertDialog(
                        title: Text('注意'),
                        content: Text('确认提交吗？'),
                        actions: <Widget>[
                          new Container(
                            child: FlatButton(
                              child: new Text(
                                "取消",
                                style: TextStyle(color: Colors.black),
                              ),
                              onPressed: () {
                                Navigator.pop(context);
                              },
                            ),
                          ),
                          new Container(
                            child: FlatButton(
                              child: new Text(
                                "确定",
                                style: TextStyle(color: Colors.red),
                              ),
                              onPressed: () {
                                Navigator.pop(context);
                                this.addImage();
                              },
                            ),
                          ),
                        ],
                      );
                    });
              },
              child: Container(
                height: Styles.MainButtonHeight,
                alignment: Alignment.center,
                child: Text(
                  '确定提交',
                  style: TextStyle(
                      fontSize: Styles.MainButtonTextFont, color: Colors.white),
                ),
              ),
            ),
          ),
        ));
  }
}
